package com.aaron.socket.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

public class FileSendThread extends Thread{
	
	public static final int TRY_TIME = 3;
	
	private String filePath;
	private Socket  soc;
	private InetSocketAddress addr;
	private OutputStream writer;
	private InputStream  reader;
	
	public FileSendThread(String filePath, String address,int port) throws UnknownHostException{
		this.filePath = filePath;
		this.addr     = new InetSocketAddress(address,port);     
	}
	
	@Override
	public void run(){
		 try {
			soc = new Socket();
			int time = TRY_TIME;
			while(!soc.isConnected() && (time--) > 0){
				System.out.println("尝试第"+(3-time)+"次连接...");
				soc.connect(addr, 30000);
			}
			if(0 == time){
				System.out.println("连接失败!");
				return;
			}
			else{
				System.out.println("连接成功!");
			}
			writer = soc.getOutputStream();
			reader = new FileInputStream(filePath);
			byte[] buffer = new byte[512];
			int len = 0;
			while((len = reader.read(buffer)) > 0){
				writer.write(buffer, 0, len);
				writer.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("Socket建立连接异常！");
		}
		finally{
			if(null != soc){
				try {
					soc.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("Socket关闭异常!");
				}
			}
			
			if(null != writer){
				try {
					writer.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("输出流关闭异常!");
				}
			}
			
			if(null != reader){
				try {
					reader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					System.out.println("输出流关闭异常!");
				}
			}
			
		}
	}

}
